"""
简化的异常类体系
Simplified exception class hierarchy for SchedulerAI
"""

from typing import Any, Dict


class SchedulerError(Exception):
    """基础调度器异常 - Base scheduler exception"""

    def __init__(self, message: str, error_code: str = None, suggestions: list = None):
        super().__init__(message)
        self.message = message
        self.error_code = error_code or "SCHEDULER_ERROR"
        self.suggestions = suggestions or []

    def to_dict(self):
        """转换为字典格式，用于API响应"""
        return {
            "error_code": self.error_code,
            "error_message": self.message,
            "suggestions": self.suggestions,
        }


class DataParsingError(SchedulerError):
    """数据解析异常 - Data parsing exception"""

    def __init__(self, message: str, line_number: int = None, column_name: str = None):
        suggestions = [
            "检查CSV文件格式是否正确",
            "确保必需的列存在：ID, Name, Duration, Predecessors, 划分条件",
            "验证数据类型是否匹配（ID和Duration应为数字）",
        ]

        if line_number:
            message = f"第{line_number}行: {message}"
            suggestions.append(f"检查第{line_number}行的数据格式")

        if column_name:
            suggestions.append(f"检查列'{column_name}'的数据格式")

        super().__init__(message, "DATA_PARSING_ERROR", suggestions)
        self.line_number = line_number
        self.column_name = column_name


class OptimizationError(SchedulerError):
    """优化求解异常 - Optimization solving exception"""

    def __init__(self, message: str, solver_status: str = None):
        suggestions = [
            "检查项目数据是否存在循环依赖",
            "验证资源约束是否合理",
            "尝试增加求解时间限制",
            "检查工序持续时间是否为正数",
        ]

        if solver_status == "INFEASIBLE":
            suggestions.extend(
                ["项目可能无解，检查资源容量是否足够", "验证前置关系是否存在冲突"]
            )
        elif solver_status == "MODEL_INVALID":
            suggestions.extend(["检查输入数据的完整性", "验证约束条件是否有效"])

        super().__init__(message, "OPTIMIZATION_ERROR", suggestions)
        self.solver_status = solver_status


class ResourceConstraintError(SchedulerError):
    """资源约束异常 - Resource constraint exception"""

    def __init__(
        self,
        message: str,
        resource_type: str = None,
        required: int = None,
        available: int = None,
    ):
        suggestions = [
            "增加资源容量配置",
            "检查资源需求是否合理",
            "考虑调整工序的资源分配",
        ]

        if resource_type and required and available:
            suggestions.append(
                f"资源'{resource_type}'需要{required}个单位，但只有{available}个可用"
            )

        super().__init__(message, "RESOURCE_CONSTRAINT_ERROR", suggestions)
        self.resource_type = resource_type
        self.required = required
        self.available = available


class ValidationError(SchedulerError):
    """数据验证异常 - Data validation exception"""

    def __init__(self, message: str, field_name: str = None, field_value=None):
        suggestions = [
            "检查输入参数的格式和范围",
            "参考API文档了解正确的参数格式",
            "验证必需字段是否提供",
        ]

        if field_name:
            suggestions.append(f"检查字段'{field_name}'的值")

        super().__init__(message, "VALIDATION_ERROR", suggestions)
        self.field_name = field_name
        self.field_value = field_value


class ConfigurationError(SchedulerError):
    """配置错误异常 - Configuration error exception"""

    def __init__(self, message: str, config_key: str = None):
        suggestions = [
            "检查配置参数的格式",
            "参考文档了解正确的配置选项",
            "使用默认配置进行测试",
        ]

        if config_key:
            suggestions.append(f"检查配置项'{config_key}'的设置")

        super().__init__(message, "CONFIGURATION_ERROR", suggestions)
        self.config_key = config_key


class FileProcessingError(SchedulerError):
    """文件处理异常 - File processing exception"""

    def __init__(self, message: str, file_name: str = None, encoding: str = None):
        suggestions = [
            "检查文件是否存在且可读",
            "验证文件格式是否为CSV",
            "尝试使用UTF-8编码保存文件",
        ]

        if encoding:
            suggestions.append(f"尝试使用{encoding}编码读取文件")

        super().__init__(message, "FILE_PROCESSING_ERROR", suggestions)
        self.file_name = file_name
        self.encoding = encoding


# 为了兼容现有代码，添加旧的异常类别名
class ModelingError(SchedulerError):
    """建模错误异常 - 兼容旧代码"""

    def __init__(self, message: str):
        super().__init__(
            message,
            "MODELING_ERROR",
            ["检查数据模型的完整性", "验证约束条件是否正确", "确保变量定义合理"],
        )


class SolvingError(OptimizationError):
    """求解错误异常 - 兼容旧代码"""

    def __init__(self, message: str, solver_status: str = None):
        super().__init__(message, solver_status)


class WorkerValidationError(ValidationError):
    """工种验证错误异常"""
    
    def __init__(self, message: str, worker_type: str = None, activity_id: str = None):
        suggestions = [
            "检查工种名称是否正确",
            "验证工人数量是否为正整数",
            "确保工种配置存在",
        ]
        
        if worker_type:
            suggestions.append(f"检查工种'{worker_type}'的配置")
        if activity_id:
            suggestions.append(f"检查工序'{activity_id}'的工种需求")
            
        super().__init__(message, "worker_type" if worker_type else "activity_id", 
                        worker_type if worker_type else activity_id)
        self.worker_type = worker_type
        self.activity_id = activity_id
        
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        result = super().to_dict()
        result.update({
            "type": "worker_validation",
            "worker_type": self.worker_type,
            "activity_id": self.activity_id,
        })
        return result


class WorkerCapacityError(ResourceConstraintError):
    """工种容量不足错误异常"""
    
    def __init__(self, message: str, worker_type: str, required: int, available: int):
        suggestions = [
            f"增加'{worker_type}'工种的容量配置",
            "检查工种需求分配是否合理",
            "考虑调整工序的工种分配",
            f"当前需要{required}个{worker_type}，但只有{available}个可用",
        ]
        
        super().__init__(message, worker_type, required, available)
        self.worker_type = worker_type
